//
//  HttpClient.m
//  OCUI
//
//  Created by login on 15-6-25.
//
//

#import "HttpClient.h"
#import "SBJSON.h"
#import "ASIFormDataRequest.h"
static ASIHTTPRequest *request;
static UIActivityIndicatorView *indicator;

@implementation HttpClient
+ (void)initialize
{
    request = [[ASIHTTPRequest alloc]init];
}

+ (void)getRequestWithProgress:(UIView *)view and:(NSString *)urlString and:(NSDictionary *)urlDic requestType:(RequestType)type andResult:(void(^)(NSArray *mainArray))block
{
//    等待视图
    
    UIActivityIndicatorView *isR = (UIActivityIndicatorView *)[view viewWithTag:1111];
    if (!isR) {
        indicator = [[UIActivityIndicatorView alloc]init];
        indicator.frame = CGRectMake(0, 0, 50, 50);
        [indicator setCenter:view.center];
        [indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        indicator.tag = 1111;
        [view addSubview:indicator];
    }else{
        indicator = isR;
    }
    
//    子线程加载数据
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if (indicator.isAnimating == NO) {
            [indicator startAnimating];
        }
        
        [HttpClient getRequestSync:urlString and:urlDic requestType:GET andResult:^(NSArray *receiveArray) {
            
            if (indicator.isAnimating == YES) {
                [indicator stopAnimating];
            }
            [indicator removeFromSuperview];

            dispatch_async(dispatch_get_main_queue(), ^{
                
                block(receiveArray);
                
            });
        }];
    });
    

}
#pragma mark - GET同步请求
+ (void)getRequestSync:(NSString *)urlString and:(NSDictionary *)urlDic requestType:(RequestType)type andResult:(void(^)(NSArray *receiveArray))block
{
    
//    将字典中所有key和value连接起来
    NSArray *allKey = [urlDic allKeys];
    NSString *result = nil;
    for (int i=0; i<allKey.count; i++) {
        
        NSString *value = [NSString stringWithFormat:@"%@=%@&",allKey[i],urlDic[allKey[i]]];
        result = [NSString stringWithFormat:@"%@%@",result,value];
    }
//    把最后一个&去掉
    NSRange range = NSMakeRange(0, result.length-1);
    NSString *subString = [result substringWithRange:range];
    
//    得到请求地址
    NSString *requestUrl = [NSString stringWithFormat:@"%@?%@",urlString,subString];
//    url不支持中文 需要编码
    NSString *encodeString = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:encodeString];
    request = [ASIHTTPRequest requestWithURL:url];
//    request.delegate = self;
//    [request setShouldAttemptPersistentConnection:NO];

    [request setCompletionBlock:^{
        if ([request responseData]) {
            NSData *receive = [request responseData];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:receive options:NSJSONReadingMutableContainers error:nil];
            SBJsonWriter *writer = [[SBJsonWriter alloc]init];
            NSString *value = [writer stringWithObject:dic];
            NSArray *array = [[[SBJsonParser alloc]init]objectWithString:value];
            
            block(array);//将下载的数组传出
            
        }
        
    }];
    [request startSynchronous];
    
    [request setFailedBlock:^{
        NSError *error = [request error];
        NSLog ( @"error:%@" ,[error userInfo ]);

    }];
    
}
#pragma mark - GET异步请求
- (void)getRequestAsyWithProgress:(UIView *)view and:(NSString *)urlString and:(NSDictionary *)urlDic requestType:(RequestType)type;
{
    
    UIActivityIndicatorView *isR = (UIActivityIndicatorView *)[view viewWithTag:1112];
    if (!isR) {
        indicator = [[UIActivityIndicatorView alloc]init];
        indicator.frame = CGRectMake(0, 0, 50, 50);
        [indicator setCenter:view.center];
        [indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        indicator.tag = 1112;
        [view addSubview:indicator];
    }else{
        indicator = isR;
    }
    [indicator startAnimating];
    
    NSArray *allKey = [urlDic allKeys];
    NSString *result = @"";
    for (int i=0; i<allKey.count; i++) {
        
        NSString *value = [NSString stringWithFormat:@"%@=%@&",allKey[i],urlDic[allKey[i]]];
        result = [NSString stringWithFormat:@"%@%@",result,value];
    }
    //    把最后一个&去掉
    NSRange range = NSMakeRange(0, result.length-1);
    NSString *subString = [result substringWithRange:range];
    
    //    得到请求地址
    NSString *requestUrl = [NSString stringWithFormat:@"%@?%@",urlString,subString];
    //    url不支持中文 需要编码
    NSString *encodeString = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:encodeString];
    NSLog(@"%@",requestUrl);
    request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *responseData = [request responseData];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    SBJsonWriter *writer = [[SBJsonWriter alloc]init];
    NSString *value = [writer stringWithObject:dic];
    NSDictionary *dict = [[[SBJsonParser alloc]init]objectWithString:value];

    if (indicator.isAnimating == YES) {
        [indicator stopAnimating];
    }
    [indicator removeFromSuperview];
    
    [self.delegate sendRequestDataArray:dict];
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void)dealloc
{
    [request setDelegate:nil];
    [request cancel];
}


@end
